package com.common.app.dialog

import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextPaint
import android.text.style.ClickableSpan
import android.text.style.UnderlineSpan
import android.view.*
import android.view.View.OnClickListener
import androidx.core.content.ContextCompat
import com.common.app.R
import com.common.app.databinding.DialogActivitySercurityLayoutBinding
import com.common.base.utils.ViewUtils
import com.zrq.spanbuilder.Spans

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：24/2/2023
 *
 * 描述：隐私政策对话框
 *
 * 修订历史：
 *
 */
class PrivacyPolicyDialog(context: Context, mListener: OnPrivacyPolicyClickListener?) :
    Dialog(context),OnClickListener {
    private var binding: DialogActivitySercurityLayoutBinding? = null
    private val context: Context
    private val mListener: OnPrivacyPolicyClickListener?

    init {
        setDialogTheme()
        setCanceledOnTouchOutside(false)
        this.context = context
        this.mListener = mListener
    }

    /**
     * set dialog theme(设置对话框主题)
     */
    private fun setDialogTheme() {
        requestWindowFeature(Window.FEATURE_NO_TITLE) // android:windowNoTitle
        window?.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND) // android:backgroundDimEnabled默认是true的
        window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) // android:windowBackground
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DialogActivitySercurityLayoutBinding.inflate(LayoutInflater.from(getContext()))
        binding?.root?.let { setContentView(it) }
        initView()
        initData()
        initEvent()
    }

    private fun initData() {}
    private fun initEvent() {
        binding?.positiveButton?.setOnClickListener(this)
        binding?.negativeButton?.setOnClickListener(this)
    }

    private fun initView() {
        tMode()
    }

    override fun onBackPressed() {
        //强制更新时,按返回键不隐藏dialog,方法体置空即可
    }

    override fun show() {
        //获取当前Activity所在的窗体
        val dialogWindow = window
        //设置Dialog从窗体底部弹出
        dialogWindow?.setGravity(Gravity.CENTER)
        dialogWindow?.decorView?.setPadding(150, 0, 150, 0)
        val lp = dialogWindow?.attributes
        //设置宽
        lp?.width = WindowManager.LayoutParams.MATCH_PARENT
        //设置高
        lp?.height = WindowManager.LayoutParams.WRAP_CONTENT
        dialogWindow?.attributes = lp
        //显示对话框
        dialogWindow?.setGravity(Gravity.CENTER)
        //设置dialog的动画效果
        dialogWindow?.setWindowAnimations(R.style.bottomShowStyle)
        super.show()
    }

    /**
     * 使用富文本SpannableStringBuilder设置点击事件
     */
    private fun tMode() {
//        String mBody = App.getContext().getResources().getString(R.string.welcome_ac_privacy_body);
//        binding.activitySercurityTv.setText(updateTextStyle(mBody));
//        binding.activitySercurityTv.setMovementMethod(LinkMovementMethod.getInstance());
        binding?.activitySercurityTv?.text = Spans.builder()
            .text("亲爱的用户，为保障您的权益，在注册流程中请阅读并理解")
            .text("“用户协议”").click(binding?.activitySercurityTv, object : ClickableSpan() {
                override fun onClick(widget: View) {
                    //                        Toast.makeText(context, "用户协议", Toast.LENGTH_SHORT).show();
                    mListener?.onPrivacyServiceAgreeClick()
                }

                override fun updateDrawState(ds: TextPaint) {
                    ds.color = ContextCompat.getColor(context, R.color.c_7d92ff)
                    ds.isUnderlineText = true
                }
            })
            .text("和")
            .text("“隐私权相关政策”").click(binding?.activitySercurityTv, object : ClickableSpan() {
                override fun onClick(widget: View) {
                    //                        Toast.makeText(context, "隐私权相关政策", Toast.LENGTH_SHORT).show();
                    mListener?.onPrivacyPolicyExamineClick()
                }

                override fun updateDrawState(ds: TextPaint) {
                    ds.color = ContextCompat.getColor(context, R.color.c_7d92ff)
                    ds.isUnderlineText = true
                }
            })
            .text("的条款内容，以了解您的权利和业务(特别是加粗或下划线标注的内容)。")
            .build()
    }

    private fun updateTextStyle(content: String): SpannableStringBuilder {
        val spannableString = SpannableStringBuilder()
        spannableString.append(content)

        //使用ForegroundColorSpan添加点击事件会出现冲突
        val colorSpan: UnderlineSpan = object : UnderlineSpan() {
            override fun updateDrawState(ds: TextPaint) {
                ds.color = ContextCompat.getColor(context, R.color.c_7d92ff) //设置颜色
                ds.isUnderlineText = false //去掉下划线
            }
        }


        //使用UnderlineSpan很好的兼容这个问题
        val colorSpan1: UnderlineSpan = object : UnderlineSpan() {
            override fun updateDrawState(ds: TextPaint) {
                ds.color = ContextCompat.getColor(context, R.color.c_7d92ff) //设置颜色
                ds.isUnderlineText = false //去掉下划线
            }
        }

//        int privacyBeginIndex = content.indexOf("“");
//        int privacyEndIndex = content.indexOf("”") + 1;
//        int protocolBeginIndex = content.lastIndexOf("“");
//        int protocolEndIndex = content.lastIndexOf("”") + 1;
        val privacyBeginIndex = content.indexOf("“")
        val privacyEndIndex = content.indexOf("”") + 1
        val protocolBeginIndex = content.lastIndexOf("“")
        val protocolEndIndex = content.lastIndexOf("”") + 1
        val privacyClickableSpan: ClickableSpan = object : ClickableSpan() {
            override fun onClick(widget: View) {
                mListener?.onPrivacyServiceAgreeClick()
            }
        }
        val protocolClickableSpan: ClickableSpan = object : ClickableSpan() {
            override fun onClick(widget: View) {
                mListener?.onPrivacyPolicyExamineClick()
            }
        }
        spannableString.setSpan(
            protocolClickableSpan,
            protocolBeginIndex,
            protocolEndIndex,
            Spannable.SPAN_EXCLUSIVE_INCLUSIVE
        )
        spannableString.setSpan(
            privacyClickableSpan,
            privacyBeginIndex,
            privacyEndIndex,
            Spannable.SPAN_EXCLUSIVE_INCLUSIVE
        )

        //字体颜色一定要放在点击事件后面，不然部分手机不会修改颜色
        spannableString.setSpan(
            colorSpan,
            protocolBeginIndex,
            protocolEndIndex,
            Spannable.SPAN_EXCLUSIVE_INCLUSIVE
        )
        spannableString.setSpan(
            colorSpan1,
            privacyBeginIndex,
            privacyEndIndex,
            Spannable.SPAN_EXCLUSIVE_INCLUSIVE
        )
        return spannableString
    }

    /**
     *
     */
    interface OnPrivacyPolicyClickListener {
        fun onPrivacyServiceAgreeClick()
        fun onPrivacyPolicyExamineClick()
        fun onPrivacyPolicyAgreeClick()
        fun onPrivacyPolicyExitClick()
    }

    override fun onClick(v: View?) {
        //防止多次点击
        if (ViewUtils.isFastClick()) return

        when (v) {
            binding?.positiveButton ->mListener?.onPrivacyPolicyExitClick()
            binding?.negativeButton ->mListener?.onPrivacyPolicyAgreeClick()
        }
    }
}